<?php
class hschool_course{
	public $info_array = array();
	public $page_array = array();
	public $tree_array = array();
	public static $all_course_array = array();

	static function &instance() {
		static $object;
		if(empty($object)) {
			$object = new self();
		}
		return $object;
	}

	/*
	*	取出一个课程信息
	*/
	public function get_one($id='') {
		$info = array();
		if($id){
			$sql = "SELECT * FROM ".DB::table('course')." WHERE id='".$id."' LIMIT 1";
			$info = DB::fetch_first($sql);	
		}
		return $info;
	}

	/*
	*	创建课程
	*/
	public function add() {
		global $_G;
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
		if(!empty($is_submit)){
			@file_put_contents($_SERVER['DOCUMENT_ROOT'].'/data/logs/room/'.date('Y-m-d',time()).'houtai.log',getglobal('user_id').'★★★★'.$_SERVER['REMOTE_ADDR'].'★houtai'.PHP_EOL,FILE_APPEND);
			$id = isset($_REQUEST['id']) ? $_REQUEST['id']:'';
            $flag = isset($_REQUEST['flag']) ? $_REQUEST['flag']:0;
            $expiryday = ((strtotime($_REQUEST['end_time'])+86399) - strtotime($_REQUEST['start_time']))/(3600*24);
            $d_string = isset($_REQUEST['d_string']) ? $_REQUEST['d_string']:'';
            if($d_string){
                $course_cateid_array = $this->get_course_cateid($d_string);
            }
			$data = array(
				//'dept_id'=>$_G['dept_id'],
				'name' => $_REQUEST['name'],
				'grade_id' => $_REQUEST['grade_id'],
				'subject_id' => $_REQUEST['subject_id'],
				'term' => $_REQUEST['term'],
				'title_page' => $_REQUEST['title_page'],
				'type' => $_REQUEST['type'],
				'price' => $_REQUEST['price'],
                'introduction' => $_REQUEST['introduction'],
				'brief' => $_REQUEST['brief'],
				//'create_id' => $_G['user_id'],
				'start_time' => strtotime($_REQUEST['start_time']),
				'end_time' => strtotime($_REQUEST['end_time'])+86399,
				'expiryday' => ceil($expiryday),
				'flag' => $flag,
				'dateline' => TIMESTAMP,
				'related_id' => $_REQUEST['related_id'],
				'issue' => $_REQUEST['issue'],
				'frontpage_sort' => $_REQUEST['frontpage_sort'],
                'course_cateid' => $_REQUEST['course_cateid'],
                'course_hour_num' => trim($_REQUEST['course_hour_num']),
                'course_cate_custom' => trim($_REQUEST['course_cate_custom'])
			);
            if(!empty($course_cateid_array)){
                $data['course_cateid1'] = $data['course_cateid2'] = $data['course_cateid3'] = 0;
                if($course_cateid_array[1]){
                   $data['course_cateid1']=$course_cateid_array[1];
                }
                if($course_cateid_array[2]){
                   $data['course_cateid2']=$course_cateid_array[2];
                }
                if($course_cateid_array[3]){
                   $data['course_cateid3']=$course_cateid_array[3];
                }
            }
			if($id){
				$effect = DB::update('course',$data,array('id'=>$id));
			}else{
                $data['create_id']=$_G['user_id'];
                $data['dept_id']=$_REQUEST['dept_id'];
                //DEBUG 如果没有选择网校 默认自己网校
                if(empty($data['dept_id'])){
                    //DEBUG 取出用户所属网校 此处为处理一人多网校问题
                    $sql = "SELECT ou_d_id FROM ".DB::table('org_user')." WHERE ou_user_id='".$_G['user_id']."' LIMIT 1";
                    $sm_id = DB::result_first($sql);
                    if($sm_id){
                        $data['dept_id']=$sm_id;
                    }
                }
				$effect = DB::insert('course',$data,1);
			}
			if($effect){
				self::return_json(false,'操作成功');
			}else{
				self::return_json();
			}
		}else{
			$grade_array = $this->get_grade_array();
			$subject_array = $this->get_subject_array();
			$term_array = $this->get_term_array();
			$type_array = $this->get_type_array();
            //DEBUG 课程分类数组数据
            $system_course_cate = system_course_cate();
            //DEBUG 获取下属或我管理的网校 开始
            $hschool_dept = load_class('hschool','dept');
            $d_id_array = array();
            if($hschool_dept){
                $d_id_array=array();
                $d_id_array = $hschool_dept->get_sub_tree($_G['dept_id'],2);
                if(!empty($d_id_array)){
                    $d_id_array=array_keys($hschool_dept->tree2array($d_id_array));
                }
                if($_G['member']['is_dept_master']){
                    //$d_id_array[] = $_G['dept_id'];
                    //DEBUG 是否网校用户
                    $sql = "SELECT d_id FROM ".DB::table('dictionary')." WHERE d_id='".$_G['dept_id']."' AND d_type=2 LIMIT 1";
                    $d_result=DB::fetch_first($sql);
                    if($d_result){
                       $d_id_array[] = $d_result['d_id']; 
                    }
                    //DEBUG 取出用户管理机构 开始
                    $sql = "SELECT ou_d_id FROM ".DB::table('org_user')." WHERE ou_user_id='".$_G['user_id']."'";
                    $d_org_result=DB::fetch_all($sql);
                    if($d_org_result){
                        foreach($d_org_result AS $key =>$value){
                            $d_id_array[] = $value['ou_d_id'];
                        }
                    }
                    //DEBUG 取出用户管理机构 结束
                }
            }
            $sql = "SELECT d_id,d_name FROM ".DB::table('dictionary')." WHERE d_id IN (".dimplode($d_id_array).") AND d_type=2 AND isdelete=0";
            $org_result = DB::fetch_all($sql);
            //DEBUG 获取下属或我管理的网校 结束
            //DEBUG 选择课程其他自定义课程分类 开始
            $course_cate_custom = DB::fetch_all("SELECT ccc_id,ccc_name FROM ".DB::table('course_cate_custom')." WHERE isdelete=0 LIMIT 200");
            //DEBUG 选择课程其他自定义课程分类 结束
			include template('admin/hschool/course_add');	
		}
	}

	/*
	*	编辑课程
	*/
	public function edit() {
		global $_G;
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
		if(!empty($is_submit)){

		}else{
			$id = isset($_REQUEST['id']) ? $_REQUEST['id']:'';
			$info = $this->get_one($id);
			$grade_array = $this->get_grade_array();
			$subject_array = $this->get_subject_array();
			$term_array = $this->get_term_array();
			$type_array = $this->get_type_array();
            //获取分类路径名称
            if($info['course_cateid3']){
                $course_cateid=$info['course_cateid3'];
            }elseif($info['course_cateid2']){
                $course_cateid=$info['course_cateid2'];
            }elseif($info['course_cateid1']){
                $course_cateid=$info['course_cateid1'];
            }
            if($course_cateid){
                $course_catename_array = $this->get_course_catename($course_cateid);
                $d_string_name = implode('->',$course_catename_array);
            }
            //DEBUG 课程分类数组数据
            $system_course_cate = system_course_cate();
            //DEBUG 获取下属或我管理的网校 开始
            $hschool_dept = load_class('hschool','dept');
            $d_id_array = array();
            if($hschool_dept){
                $d_id_array=array();
                $d_id_array = $hschool_dept->get_sub_tree($_G['dept_id'],2);
                if(!empty($d_id_array)){
                    $d_id_array=array_keys($hschool_dept->tree2array($d_id_array));
                }
                if($_G['member']['is_dept_master']){
                    //$d_id_array[] = $_G['dept_id'];
                    //DEBUG 是否网校用户
                    $sql = "SELECT d_id FROM ".DB::table('dictionary')." WHERE d_id='".$_G['dept_id']."' AND d_type=2 LIMIT 1";
                    $d_result=DB::fetch_first($sql);
                    if($d_result){
                       $d_id_array[] = $d_result['d_id']; 
                    }
                    //DEBUG 取出用户管理机构 开始
                    $sql = "SELECT ou_d_id FROM ".DB::table('org_user')." WHERE ou_user_id='".$_G['user_id']."'";
                    $d_org_result=DB::fetch_all($sql);
                    if($d_org_result){
                        foreach($d_org_result AS $key =>$value){
                            $d_id_array[] = $value['ou_d_id'];
                        }
                    }
                    //DEBUG 取出用户管理机构 结束
                }
            }
            $sql = "SELECT d_id,d_name FROM ".DB::table('dictionary')." WHERE d_id IN (".dimplode($d_id_array).") AND d_type=2 AND isdelete=0";
            $org_result = DB::fetch_all($sql);
            //DEBUG 获取下属或我管理的网校 结束
            //DEBUG 选择课程其他自定义课程分类 开始
            $course_cate_custom = DB::fetch_all("SELECT ccc_id,ccc_name FROM ".DB::table('course_cate_custom')." WHERE isdelete=0 LIMIT 200");
            //DEBUG 选择课程其他自定义课程分类 结束            
			include template('admin/hschool/course_add');
		}
	}

	/*
	*	删除课时
	*/
	public function del() {
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
		if(!empty($is_submit)){
			$course_ids_array = array();
			$course_ids_array = isset($_REQUEST['course_ids']) ? $_REQUEST['course_ids']:array();
			if($course_ids_array){
				$update = array(
					'isdelete'=> 1
				);
				$where = ' id IN ('.dimplode($course_ids_array).') ';
				$effects = DB::update('course',$update,$where);
				//DEBUG 后台删除课程,自动同时标记删除课时
				$where_course_hour = ' course_id IN ('.dimplode($course_ids_array).') ';
				$effects2 = DB::update('course_hour',$update,$where_course_hour);
			}
			//DEBUG 接收用户信息 end
			$this->return_json(false,'操作成功');
			echo json_encode($return_array);
		}
	}

	/*
	*	变更课时推荐状态
	*/
	public function recommend() {
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
		if(!empty($is_submit)){
			$id = isset($_REQUEST['id']) ? $_REQUEST['id']:'';
			$recommend_val = isset($_REQUEST['recommend_val']) ? $_REQUEST['recommend_val']:'';
			$update = array(
				'recommend'=> $recommend_val
			);
			$where = " id = '".$id."'";
			$effects = DB::update('course',$update,$where);
			if($effects){
				$this->return_json(false,'操作成功');
			}else{
				$this->return_json();
			}
		}
	}

	/*
	*	当前动作的首页
	*/
	public function index() {
		global $_G;
		$page_array = array();
		$sqlcount = $sql = $wheresql = $title_keyword = $pageNum = $numPerPage = '';
		$pageNum = isset($_REQUEST['pageNum']) ? $_REQUEST['pageNum'] : 1;
		$numPerPage = isset($_REQUEST['numPerPage']) ? $_REQUEST['numPerPage'] : 10;
		$pagestart = ($pageNum - 1) * $numPerPage;
		$course_type = isset($_REQUEST['course_type']) ? $_REQUEST['course_type'] : '';
		$subject_id = isset($_REQUEST['subject_id']) ? $_REQUEST['subject_id'] : '';
		$course_name = isset($_REQUEST['course_name']) ? $_REQUEST['course_name'] : '';
		//DEBUG 分层级管理课程 取出子单位建立的课程, 如果是单位管理员则带上本单位编号
		$hschool_dept = load_class('hschool','dept');
		if($hschool_dept){
			$d_id_array=array();
			$d_id_array = $hschool_dept->get_sub_tree($_G['dept_id']);
			if(!empty($d_id_array)){
				$d_id_array=array_keys($hschool_dept->tree2array($d_id_array));
			}
			if($_G['member']['is_dept_master']){
				$d_id_array[] = $_G['dept_id'];
			}
            //DEBUG 取出用户管理机构 开始
            $sql = "SELECT ou_d_id FROM ".DB::table('org_user')." WHERE ou_user_id='".$_G['user_id']."' AND is_master=1";
            $d_org_result=DB::fetch_all($sql);
            if($d_org_result){
                foreach($d_org_result AS $key =>$value){
                    $d_id_array[] = $value['ou_d_id'];
                }
            }
            //DEBUG 取出用户管理机构 结束
		}
		$wheresql .= " AND ( c.dept_id IN (".dimplode($d_id_array).") OR create_id ='".$_G['user_id']."' ) ";
		if($course_type){
			$wheresql .= " AND c.type = '".$course_type."'";
		}
		//DEBUG 如果是教研员增加学科限制
		$subject_id_array = array();
		if(32 == $_G['member']['user_role_id']){
			if(strpos($_G['member']['subjects'],',') && !empty($_G['member']['subjects'])){
				$subject_id_array = explode(',', $_G['member']['subjects']);
			}elseif(!empty($_G['member']['subjects'])){
				$subject_id_array[] = $_G['member']['subjects'];
			}
			if($subject_id && in_array($subject_id,$subject_id_array, TRUE)){
				$subject_id_array = array($subject_id);
			}
		}else{
			if($subject_id){
				$subject_id_array[] = $subject_id;
			}
		}
		if($subject_id_array){
			$wheresql .= " AND c.subject_id IN (".dimplode($subject_id_array).") ";
		}
		if($course_name){
			$wheresql .= " AND c.name LIKE '%".$course_name."%'";
		}
		$sqlcount = "SELECT count(*) from ".DB::table('course')." AS c WHERE c.isdelete=0 ".$wheresql;
		$pagetotal = DB::result_first($sqlcount);
		$sql = "SELECT c.* from ".DB::table('course')." AS c WHERE c.isdelete=0 ".$wheresql." ORDER BY c.id DESC LIMIT ".$pagestart.",".$numPerPage;
		$page_array = DB::fetch_all($sql);
		foreach($page_array AS $key => $value){
			$page_array[$key]['grade_name'] = $this->get_grade_name($value['grade_id']);
			$page_array[$key]['subject_name'] = $this->get_subject_name($value['subject_id']);
			$page_array[$key]['type_name'] = $this->get_type_name($value['type']);
		}
		//总页数
		$realpages = @ceil($pagetotal / $numPerPage);
		if($realpages <= 0){
			$realpages=1;
		}
		//前一页
		$page_pre = max(1, intval(($pageNum-1)));
		//后一页
		$page_next = min(intval(($pageNum+1)), $realpages);
		//DEBUG 获取课程类型数组
		$type_array = $this->get_type_array();
		//DEBUG 获取课程学科数组
		$subject_array = $this->get_subject_array();
		include template('admin/hschool/course');
	}

	/*
	*	变更课时选课支付人数计数
	*/
	public function count_update() {
		$is_submit = isset($_REQUEST['is_submit']) ? $_REQUEST['is_submit']:'';
		if(!empty($is_submit)){
			//DEBUG 取出所有未结束课程
			$sql = "SELECT id FROM ".DB::table('course')." WHERE end_time > '".TIMESTAMP."'";
			$result = DB::fetch_all($sql);
			//依次更新未结束课程的选课数
			foreach($result AS $key => $value){
				//DEBUG 取出课程已支付人数 并 更新选课支付人数
				$sql = "SELECT COUNT(*) FROM ".DB::table('student_course')." WHERE course_flag=1 AND course_id='".$value['id']."' AND course_cate=1";
				$course_trade_success_total = DB::result_first($sql);
				@DB::update('course',array('count'=>$course_trade_success_total),array('id'=>$value['id']));
			}
            //DEBUG 取出所有点播课程
			$sql = "SELECT id FROM ".DB::table('vod')."";
			$result = DB::fetch_all($sql);
			//依次更新未结束课程的选课数
			foreach($result AS $key => $value){
				//DEBUG 取出课程已支付人数 并 更新选课支付人数
				$sql = "SELECT COUNT(*) FROM ".DB::table('student_course')." WHERE course_flag=1 AND course_id='".$value['id']."' AND course_cate=2";
				$course_trade_success_total = DB::result_first($sql);
				@DB::update('vod',array('count'=>$course_trade_success_total),array('id'=>$value['id']));
			}
			$this->return_json(false,'操作成功');
		}
	}
    
	/*
	* 取出所在分类路径编号 默认最大层级深度3级
	*/
	private function get_course_cateid($course_cateid,$depth_level=3){
		$course_cateid_array = array();
		if($course_cateid){
			//取出根部门
			for($i=1; $i<=$depth_level; $i++){
				$sql = "SELECT d_level, d_parent_id, d_id FROM ".DB::table('dictionary')." WHERE isdelete=0 AND d_id='".$course_cateid."' LIMIT 1";
				$result = DB::fetch_first($sql);
				$course_cateid_array[$result['d_level']]=$result['d_id'];
				$course_cateid = $result['d_parent_id'];
				if(1==$result['d_level']){
					break;
				}
			}
		}
		if($course_cateid_array){
			ksort($course_cateid_array);
		}
		return $course_cateid_array;
	}
    
/*
	* 取出所在分类路径名称 默认最大层级深度3级
	*/
	private function get_course_catename($course_cateid,$depth_level=3){
		$course_catename_array = array();
		if($course_cateid){
			//取出根部门
			for($i=1; $i<=$depth_level; $i++){
				$sql = "SELECT d_level, d_parent_id, d_name FROM ".DB::table('dictionary')." WHERE isdelete=0 AND d_id='".$course_cateid."' LIMIT 1";
				$result = DB::fetch_first($sql);
				$course_catename_array[$result['d_level']]=$result['d_name'];
				$course_cateid = $result['d_parent_id'];
				if(1==$result['d_level']){
					break;
				}
			}
		}
		if($course_catename_array){
			ksort($course_catename_array);
		}
		return $course_catename_array;
	}
    
	/*
	* ajax 返回信息
	*/
	public function return_json($error='true',$message="操作失败") {
		$return_array = array(
			"error" => $error,
			"message" => $message
		);
		echo json_ext($return_array);
		die;
	}
	
	/*
	* 年级名称数组
	*/
	function get_grade_array(){
		$return = '';
		$file_path = SITE_ROOT.'./source/function/function_grade_class.php';
		if(file_exists($file_path)){
			include_once $file_path;
			$return = pub_class();
		}
		return $return;
	}
	
	/*
	* 学科名称数组
	*/
	function get_subject_array(){
		$return = '';
		$file_path = SITE_ROOT.'./source/function/function_grade_class.php';
		if(file_exists($file_path)){
			include_once $file_path;
			$return = pub_subject();
		}
		return $return;
	}

	/*
	* 学期名称数组
	*/
	function get_term_array(){
		$return = '';
		$file_path = SITE_ROOT.'./source/function/function_grade_class.php';
		if(file_exists($file_path)){
			include_once $file_path;
			$return = pub_term();
		}
		return $return;
	}

	/*
	* 课程类型名称数组
	*/
	function get_type_array(){
		$return = '';
		$file_path = SITE_ROOT.'./source/function/function_grade_class.php';
		if(file_exists($file_path)){
			include_once $file_path;
			$return = pub_type();
		}
		return $return;
	}
	
	/*
	* 年级名称转换
	*/
	function get_grade_name($grade_id){
		$return = '';
		if($grade_id){
			$grade_array = $this->get_grade_array();
			$return = $grade_array[$grade_id];
		}
		return $return;
	}
	
	/*
	* 学科名称转换
	*/
	function get_subject_name($subject_id){
		$return = '';
		if($subject_id){
			$subject_array = $this->get_subject_array();
			$return = $subject_array[$subject_id];
		}
		return $return;
	}
	
	/*
	* 课程类型名称数组
	*/
	function get_term_name($term_id){
		$return = '';
		$file_path = SITE_ROOT.'./source/function/function_grade_class.php';
		if(file_exists($file_path)){
			$term_array = $this->get_term_array();
			$return = $term_array[$term_id];;
		}
		return $return;
	}
	
	/*
	* 课程类型名称转换
	*/
	function get_type_name($type){
		$return = '';
		if($type){
			include_once SITE_ROOT.'./source/function/function_grade_class.php';
			$pub_type_array = pub_type();
			$return = $pub_type_array[$type];
		}
		return $return;
	}
	
}
?>